/**
 * 对账户的注册、登录、登出等操作。
 */
import { failDataType, successDataType } from "CustomTypes";
import { MessageBox } from "element-ui";
import { MD5 } from "crypto-js";

import { hasLoginedCloud } from "@/utils/cloud";
import { getReqDataNew } from "@/utils/http";
import {
  hasAccessToken,
  hasRefreshToken,
  initTokens,
  removeAccessToken,
  removeRefreshToken
} from "@/utils/token";
import { registUser, loginAccount, logoutAccount } from "@/apis/Account";
import userinfoStore from "store2";
import { getAesKey } from "@/utils/aeskey";
import router from "@/router";
import { rNames } from "@/config/menuConfig";

const accountName = "Account";

/**
 * 是否有 account
 */
export const hasAccount = (): boolean => userinfoStore.has(accountName);
/**
 * 获取 account
 */
export const getAccount = (): string => userinfoStore.get(accountName);
/**
 * 设置 account
 */
export const setAccount = (data: string): void =>
  userinfoStore.set(accountName, data);
/**
 * 删除 account
 */
export const removeAccount = (): void => userinfoStore.remove(accountName);
/**
 * 检验
 * 1、是否成功登录TCB云平台
 * 2、是否有两个token
 * 3、是否refreshToken没有过期
 *
 * 因为这里已经有了云平台，否决原来的token设计。
 * 只需要保证发送的数据是加密之后的数据就可以了。
 */
export const hasLogined = () => {
  const r1 = hasLoginedCloud();
  const r2 = hasAccessToken();
  const r3 = hasRefreshToken();
  const result = r1 && r2 && r3;
  return result;
};
/**
 * 登录私人账户
 */
export const login = async (account: string, password: string) => {
  /**
   * 这里需要account对应aeskey
   */
  const aesKey = getAesKey();
  const result = await loginAccount(account, MD5(password).toString(), aesKey);
  // 这里的data是加密过后的username
  const { flag, data } = getReqDataNew(result);

  if (flag) {
    console.log("登录成功");
    const result = (data as successDataType).data;
    setAccount(result);
    // 这里开始初始化两个token
    await initTokens();
    return true;
  }

  MessageBox.alert((data as failDataType).msg, {
    confirmButtonText: "确定",
    type: "error"
  });
};
/**
 * 登出私人账户
 */
export const logout = async () => {
  const username = getAccount();
  // 告诉服务器已经logout
  const result = await logoutAccount(username);
  const { flag, data } = getReqDataNew(result);

  if (flag) {
    // 删除当前的token
    removeAccessToken();
    removeRefreshToken();
    // 删除用户名
    removeAccount();
    // 跳到login页面
    router.push({ name: rNames.login });
    return;
  }

  MessageBox.alert((data as failDataType).msg, {
    confirmButtonText: "确定",
    type: "error"
  });
};
/**
 * 注册
 * @param account 账号
 * @param password 密码
 */
export const regist = async (account: string, password: string) => {
  /**
   * 这里需要account对应aeskey
   */
  const aesKey = getAesKey();
  const result = await registUser(account, MD5(password).toString(), aesKey);
  const { flag, data } = getReqDataNew(result);

  if (flag) {
    // 注册成功
    console.log("注册成功");
    return true;
  }

  MessageBox.alert((data as failDataType).msg, {
    confirmButtonText: "确定",
    type: "error"
  });
};
